package com.ruoyi.info.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.info.domain.*;
import com.ruoyi.info.mapper.AuditingMapper;
import com.ruoyi.info.vo.AuditingEnterpriseBase;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.info.mapper.CaseInfoMapper;
import com.ruoyi.info.service.ICaseInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 案例信息Service业务层处理
 * 
 * @author wangshi
 * @date 2023-06-08
 */
@Service
public class CaseInfoServiceImpl implements ICaseInfoService 
{
    @Autowired
    private CaseInfoMapper caseInfoMapper;
    @Autowired
    private AuditingMapper auditingMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    /**
     * 查询案例信息
     * 
     * @param id 案例信息主键
     * @return 案例信息
     */
    @Override
    public CaseInfo selectCaseInfoById(Long id)
    {
        return caseInfoMapper.selectCaseInfoById(id);
    }

    /**
     * 查询案例信息列表
     * 
     * @param caseInfo 案例信息
     * @return 案例信息
     */
    @Override
    public List<CaseInfo> selectCaseInfoList(CaseInfo caseInfo)
    {
        return caseInfoMapper.selectCaseInfoList(caseInfo);
    }

    /**
     * 新增案例信息
     * 
     * @param caseInfo 案例信息
     * @return 结果
     */
    @Override
    public int insertCaseInfo(CaseInfo caseInfo)
    {
        caseInfo.setCreateTime(DateUtils.getNowDate());
        return caseInfoMapper.insertCaseInfo(caseInfo);
    }

    /**
     * 修改案例信息
     * 
     * @param caseInfo 案例信息
     * @return 结果
     */
    @Override
    public int updateCaseInfo(CaseInfo caseInfo)
    {
        caseInfo.setUpdateTime(DateUtils.getNowDate());
        caseInfo.setcState("0");
        return caseInfoMapper.updateCaseInfo(caseInfo);
    }

    /**
     * 批量删除案例信息
     * 
     * @param ids 需要删除的案例信息主键
     * @return 结果
     */
    @Override
    public int deleteCaseInfoByIds(Long[] ids)
    {
        return caseInfoMapper.deleteCaseInfoByIds(ids);
    }

    /**
     * 删除案例信息信息
     * 
     * @param id 案例信息主键
     * @return 结果
     */
    @Override
    public int deleteCaseInfoById(Long id)
    {
        return caseInfoMapper.deleteCaseInfoById(id);
    }

    /**
     * 导出案例信息
     */
    @Override
    public void exportCaseInfo(HttpServletResponse response, CaseInfo caseInfo) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        List<CaseInfo> caseInfos = caseInfoMapper.selectCaseInfoList(caseInfo);
        try {
            XSSFSheet sheet = workbook.createSheet("案例信息");
            String[] labels = new String[]{
                    "单位名称",
                    "行业",
                    "行业",
                    "人员规模",
                    "适配OS",
                    "适配平台",
                    "建设内容",
                    "使用评价",
                    "应用系统名称",
                    "竣工日期",
                    "建设周期",
                    "硬件产品清单",
                    "硬件产品清单"
            };
            XSSFRow headerRow = sheet.createRow(0);
            for (int j = 0; j < labels.length; j++) {
                XSSFCell countryCell = headerRow.createCell(j);

                countryCell.setCellValue(labels[j]);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < caseInfos.size(); i++) {
                XSSFRow row = sheet.createRow(i + 1);
                //                    单位名称
                XSSFCell countryCell = row.createCell(0);
                countryCell.setCellValue(caseInfos.get(i).getcName());

//                行业
                XSSFCell countryCell1= row.createCell(1);
                List<SysDictData> productIndustry = sysDictDataMapper.selectDictDataByType("product_industry");
                for (int j = 0; j < productIndustry.size(); j++) {
                    if (caseInfos.get(i).getcIndustry().equals(productIndustry.get(j).getDictValue())) {
                        countryCell1.setCellValue(productIndustry.get(j).getDictLabel());
                        break;
                    }
                }
//                应用场景
                XSSFCell countryCell2 = row.createCell(2);
                countryCell2.setCellValue(caseInfos.get(i).getcScene());
                //                人员规模
                XSSFCell countryCell3= row.createCell(3);
                List<SysDictData> personnelSize = sysDictDataMapper.selectDictDataByType("personnel_size");
                for (int j = 0; j < personnelSize.size(); j++) {
                    if (caseInfos.get(i).getcScale().equals(personnelSize.get(j).getDictValue())) {
                        countryCell3.setCellValue(personnelSize.get(j).getDictLabel());
                        break;
                    }
                }
                //                适配OS
                XSSFCell countryCell4= row.createCell(4);
                List<SysDictData> auditionOs = sysDictDataMapper.selectDictDataByType("audition_os");
                for (int j = 0; j < auditionOs.size(); j++) {
                    if (caseInfos.get(i).getcOs().equals(auditionOs.get(j).getDictValue())) {
                        countryCell4.setCellValue(auditionOs.get(j).getDictLabel());
                        break;
                    }
                }
                //                    适配平台
                XSSFCell countryCell5 = row.createCell(5);
                countryCell5.setCellValue(caseInfos.get(i).getcPlatform());
                //                    建设内容
                XSSFCell countryCell6 = row.createCell(6);
                countryCell6.setCellValue(caseInfos.get(i).getcContent());
                //                    使用评价
                XSSFCell countryCell7= row.createCell(7);
                countryCell7.setCellValue(caseInfos.get(i).getcEvaluate());
                //                    应用系统名称
                XSSFCell countryCell8= row.createCell(8);
                countryCell8.setCellValue(caseInfos.get(i).getcAppName());
                //                    竣工日期
                XSSFCell countryCell9= row.createCell(9);
                countryCell9.setCellValue(sdf.format(caseInfos.get(i).getcCompletionDate()));
                //                    建设周期
                XSSFCell countryCell10= row.createCell(10);
                countryCell10.setCellValue(caseInfos.get(i).getcConstructionCycle());
                //                    硬件产品清单
                XSSFCell countryCell11= row.createCell(11);
                countryCell11.setCellValue(caseInfos.get(i).getcHardwareInventory());
                //                    软件产品清单
                XSSFCell countryCell12= row.createCell(12);
                countryCell12.setCellValue(caseInfos.get(i).getcSoftwareInventory());
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("utf-8");
                workbook.write(response.getOutputStream());
            }
        } finally {
            workbook.close();
        }

    }

    /**
     * 导入案例信息 并渲染成数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int templateRender(MultipartFile file) throws IOException {
        // 创建工作簿对象
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        try {

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            int i = 0;
            // 遍历行
            for (Row row : sheet) {
                if(i == 0){
                    i++;
                    continue;
                }
                CaseInfo caseInfo = new CaseInfo();
                int j = 0;
                // 遍历单元格
                for (Cell cell : row) {

                    // 获取单元格的值
                    CellType type = cell.getCellType();
                    String value = "";
                    if (type == CellType.STRING) {
                        value = cell.getStringCellValue();

                    } else if (type == CellType.NUMERIC) {
                        if(j == 9){
                            value = sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
                        }else{
                            value = String.valueOf(cell.getNumericCellValue());
                        }

                    } else if (type == CellType.BOOLEAN) {
                        value = String.valueOf(cell.getBooleanCellValue());
                    }

                    if(j == 0){
                        List<SysDictData> productIndustry = sysDictDataMapper.selectDictDataByType("product_industry");
                        for (int K= 0; K < productIndustry.size(); K++) {
                            if (value.equals(productIndustry.get(K).getDictLabel())) {
                                caseInfo.setcIndustry(productIndustry.get(K).getDictValue());
                                break;
                            }
                        }
                    }else if(j == 1){
                        caseInfo.setcScene(value);
                    }else if(j == 2){
                        List<SysDictData> personnelSize = sysDictDataMapper.selectDictDataByType("personnel_size");
                        for (int K= 0; K < personnelSize.size(); K++) {
                            if (value.equals(personnelSize.get(K).getDictLabel())) {
                                caseInfo.setcScale(personnelSize.get(K).getDictValue());
                                break;
                            }
                        }
                    }else if(j == 3){
                        List<SysDictData> auditionOs = sysDictDataMapper.selectDictDataByType("audition_os");
                        for (int K= 0; K < auditionOs.size(); K++) {
                            if (value.equals(auditionOs.get(K).getDictLabel())) {
                                caseInfo.setcOs(auditionOs.get(K).getDictValue());
                                break;
                            }
                        }
                    }else if(j == 4){
                        caseInfo.setcPlatform(value);

                    }else if(j == 5){
                        caseInfo.setcContent(value);
                    }else if(j == 6){
                        caseInfo.setcEvaluate(value);
                    }else if(j == 7){
                        caseInfo.setcAppName(value);
                    }else if(j == 8){
                        caseInfo.setcCompletionDate(sdf.parse(value));
                    }else if(j == 9){
                        caseInfo.setcConstructionCycle(value);
                    }else if(j == 10){
                        caseInfo.setcHardwareInventory(value);
                    }else if(j == 11){
                        caseInfo.setcSoftwareInventory(value);
                    }


                    j++;
                }
                caseInfo.setcName("单位一");
                caseInfoMapper.insertCaseInfo(caseInfo);
            }
            return 1;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        } finally {
            workbook.close();
        }
    }
    /**
     * 导出案例信息模板
     */
    @Override
    public void templateDownload(HttpServletResponse response) throws IOException{
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            XSSFSheet sheet = workbook.createSheet("案例信息");
            String[] labels = new String[]{
//                    "单位名称",
                    "行业",
                    "行业",
                    "人员规模",
                    "适配OS",
                    "适配平台",
                    "建设内容",
                    "使用评价",
                    "应用系统名称",
                    "竣工日期",
                    "建设周期",
                    "硬件产品清单",
                    "硬件产品清单"
            };
            XSSFRow headerRow = sheet.createRow(0);
            for (int j = 0; j < labels.length; j++) {
                XSSFCell countryCell = headerRow.createCell(j);

                countryCell.setCellValue(labels[j]);
            }
            XSSFRow row = sheet.createRow(1);
            for (int i = 0; i < labels.length; i++) {
                // 创建单元格并设置值
                Cell cell = row.createCell(i);
                if(i == 0){
                    List<SysDictData> productIndustry = sysDictDataMapper.selectDictDataByType("product_industry");
                    String[] dictLabels = new String[productIndustry.size()];
                    for (int j = 0; j < productIndustry.size(); j++) {
                        dictLabels[j] = productIndustry.get(j).getDictLabel();
                    }
                    // 设置单元格数据验证
                    DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                    DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                    CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                    DataValidation validation = validationHelper.createValidation(constraint, addressList);
                    sheet.addValidationData(validation);
                }
                if(i == 2){
                    List<SysDictData> personnelSize = sysDictDataMapper.selectDictDataByType("personnel_size");
                    String[] dictLabels = new String[personnelSize.size()];
                    for (int j = 0; j < personnelSize.size(); j++) {
                        dictLabels[j] = personnelSize.get(j).getDictLabel();
                    }
                    // 设置单元格数据验证
                    DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                    DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                    CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                    DataValidation validation = validationHelper.createValidation(constraint, addressList);
                    sheet.addValidationData(validation);
                }
                if(i == 3){
                    List<SysDictData> auditionOs = sysDictDataMapper.selectDictDataByType("audition_os");
                    String[] dictLabels = new String[auditionOs.size()];
                    for (int j = 0; j < auditionOs.size(); j++) {
                        dictLabels[j] = auditionOs.get(j).getDictLabel();
                    }
                    // 设置单元格数据验证
                    DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                    DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                    CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                    DataValidation validation = validationHelper.createValidation(constraint, addressList);
                    sheet.addValidationData(validation);
                }

                if(i == 8){
                    // 设置日期格式
                    String dateFormat = "yyyy-mm-dd";
                    DataFormat dataFormat = workbook.createDataFormat();
                    CellStyle dateStyle = workbook.createCellStyle();
                    dateStyle.setDataFormat(dataFormat.getFormat(dateFormat));
                    cell.setCellStyle(dateStyle);
                }
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            workbook.write(response.getOutputStream());
        }finally {
            workbook.close();
        }
    }
    /**
     * 案例审核
     * @param auditingEnterpriseBase 案例审核字段
     * @return
     */
    @Override
    public int auditingCaseInfo(AuditingEnterpriseBase auditingEnterpriseBase){
        CaseInfo caseInfo = new CaseInfo();
        caseInfo.setId(auditingEnterpriseBase.getaPId());
        caseInfo.setcState(auditingEnterpriseBase.getEbState());
        caseInfo.setUpdateBy(auditingEnterpriseBase.getCreateBy());
        caseInfo.setUpdateTime(DateUtils.getNowDate());
        int i = caseInfoMapper.updateCaseInfo(caseInfo);
        if(i>0){
            Auditing auditing = new Auditing();
            auditing.setpName("casc_info");
            auditing.setaPId(auditingEnterpriseBase.getaPId());
            auditing.setaInfo(auditingEnterpriseBase.getaInfo());
            auditing.setaState(auditingEnterpriseBase.getEbState());
            auditing.setCreateTime(DateUtils.getNowDate());
            auditing.setCreateBy(auditingEnterpriseBase.getCreateBy());
            return auditingMapper.insertAuditing(auditing);
        }
        return 0;
    }
}
